package com.ftwj.controller;

import com.ftwj.service.CaptchaService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Slf4j
@RestController
public class CaptchaController {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private DefaultKaptcha captchaProducer;

    @GetMapping("/api/captcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        // 设置响应头，防止图片缓存
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        // 生成验证码文本并存储到会话
        String captchaText = captchaService.generateCaptcha(session);

        // 创建验证码图像
        BufferedImage captchaImage = captchaProducer.createImage(captchaText);

        // 将图像写入响应流
        try {
            javax.imageio.ImageIO.write(captchaImage, "jpeg", response.getOutputStream());
        } catch (IOException e) {
            // 记录日志并返回错误响应
            log.error("Failed to write captcha image to response", e);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to generate captcha");
        }
    }
    @PostMapping("/api/verifyCaptcha")
    public boolean validateCaptcha(HttpSession session, @RequestParam String captchaInput) {
        return captchaService.validateCaptcha(session, captchaInput);
    }
}
